﻿<?php
require_once dirname(__FILE__) . '/config.php';
require_once 'carrier_map.php';
session_start();

// 创建数据库连接
function getDBConnection() {
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die('连接失败: ' . $conn->connect_error);
    }
    $conn->set_charset('utf8');
    return $conn;
}

$result = null;
$error = null;

// 获取查询历史
if (isset($_SESSION['username'])) {
    $conn = getDBConnection();
    $username = $_SESSION['username'];
    $stmt = $conn->prepare("SELECT * FROM tracking_history WHERE name = ? ORDER BY query_time DESC LIMIT 10");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $history = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    $conn->close();
}

// 支持通过GET参数自动查询
if (empty($_POST) && isset($_GET['tracking_number'])) {
    $_POST['tracking_number'] = $_GET['tracking_number'];
    if (isset($_GET['carrier'])) {
        $_POST['carrier'] = $_GET['carrier'];
    }
    $_SERVER['REQUEST_METHOD'] = 'POST';
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $tracking_number = $_POST['tracking_number'];
    $carrier = isset($_POST['carrier']) ? $_POST['carrier'] : '';
    
    // 调用快递查询API
    $url = API_HOST . API_PATH . "?no=" . urlencode($tracking_number);
    if (!empty($carrier)) {
        $url .= "&type=" . $carrier;
    }
    
    $headers = array("Authorization:APPCODE " . API_APPCODE);
    
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    
    list($header, $body) = explode("\r\n\r\n", $response, 2);
    
    if ($httpCode == 200) {
        $result = json_decode($body, true);
        // 判断API返回是否有效（如无result或无list则视为失败）
        if (!isset($result['result']) || empty($result['result']['list'])) {
            $error = "查询失败，未查到该单号信息，请检查单号是否正确。";
            $result = null;
        } else {
            // 获取最新状态
            $latest_status = '';
            $express_status = '';
            if (isset($result['result']['list'][0]['status'])) {
                $latest_status = $result['result']['list'][0]['status'];
                // 添加调试信息
                error_log("最新状态: " . $latest_status);
                error_log("deliverystatus: " . (isset($result['result']['deliverystatus']) ? $result['result']['deliverystatus'] : '未设置'));
            }
            // 严格根据 deliverystatus 字段映射快递状态
            if (isset($result['result']['deliverystatus'])) {
                switch ($result['result']['deliverystatus']) {
                    case '0':
                        $express_status = '揽件中';
                        break;
                    case '1':
                        $express_status = '运送中';
                        break;
                    case '2':
                        $express_status = '派送中';
                        break;
                    case '3':
                        $express_status = '已妥投';
                        break;
                    case '4':
                        $express_status = '派送失败';
                        break;
                    case '5':
                        $express_status = '疑难件';
                        break;
                    case '6':
                        $express_status = '退件签收';
                        break;
                    default:
                        $express_status = '运送中';
                }
                error_log("根据deliverystatus判断的状态: " . $express_status);
            } else if (isset($result['result']['issign']) && $result['result']['issign'] == '1') {
                $express_status = '已妥投';
                error_log("根据issign判断的状态: " . $express_status);
            } else {
                // 兜底：用文本判断
                if (strpos($latest_status, '签收') !== false || strpos($latest_status, '妥投') !== false || strpos($latest_status, '代收') !== false || strpos($latest_status, '已投递') !== false || strpos($latest_status, '已送达') !== false) {
                    $express_status = '已妥投';
                } elseif (strpos($latest_status, '派送中') !== false || strpos($latest_status, '正在派送') !== false || strpos($latest_status, '派送员') !== false || strpos($latest_status, '配送中') !== false || strpos($latest_status, '派送') !== false) {
                    $express_status = '派送中';
                } elseif (strpos($latest_status, '待派送') !== false || strpos($latest_status, '等待派送') !== false) {
                    $express_status = '待派送';
                } else {
                    $express_status = '运送中';
                }
                error_log("根据文本判断的状态: " . $express_status);
            }
            // 如果用户已登录，更新查询记录
            if (isset($_SESSION['username'])) {
                $conn = getDBConnection();
                // 获取API返回的快递公司
                $api_carrier = isset($result['result']['type']) ? $result['result']['type'] : '';
                // 检查是否已存在该单号的记录
                $stmt = $conn->prepare("SELECT id FROM tracking_history WHERE name = ? AND tracking_number = ?");
                $stmt->bind_param("ss", $_SESSION['username'], $tracking_number);
                $stmt->execute();
                $existing = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                if ($existing) {
                    // 更新现有记录
                    $stmt = $conn->prepare("UPDATE tracking_history SET carrier = ?, express_status = ?, status = ?, query_time = CURRENT_TIMESTAMP WHERE id = ?");
                    $stmt->bind_param("sssi", $api_carrier, $express_status, $latest_status, $existing['id']);
                } else {
                    // 插入新记录
                    $stmt = $conn->prepare("INSERT INTO tracking_history (name, tracking_number, carrier, express_status, status) VALUES (?, ?, ?, ?, ?)");
                    $stmt->bind_param("sssss", $_SESSION['username'], $tracking_number, $api_carrier, $express_status, $latest_status);
                }
                $stmt->execute();
                $stmt->close();
                // 重新获取查询历史
                $conn = getDBConnection();
                $stmt = $conn->prepare("SELECT * FROM tracking_history WHERE name = ? ORDER BY query_time DESC LIMIT 10");
                $stmt->bind_param("s", $_SESSION['username']);
                $stmt->execute();
                $history = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
                $stmt->close();
                $conn->close();
            }
        }
    } else {
        $error = "查询失败，请检查快递单号是否正确";
        $result = null;
    }
    
    curl_close($curl);
}
?>

<style>
:root {
    --primary-color: #4a6bff;
    --secondary-color: #6c8eff;
    --background-gradient: linear-gradient(135deg, #f5f7ff 0%, #e8edff 100%);
    --card-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    --hover-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
    --success-color: #00c853;
    --warning-color: #ff9800;
    --error-color: #ff4757;
}

body {
    background: var(--background-gradient);
    min-height: 100vh;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    margin: 0;
    padding: 0;
}

/* 加载动画 */
.loading {
    display: none;
    text-align: center;
    padding: 2rem;
}

.loading-spinner {
    width: 40px;
    height: 40px;
    border: 4px solid rgba(74, 107, 255, 0.1);
    border-radius: 50%;
    border-top-color: var(--primary-color);
    animation: spin 1s ease-in-out infinite;
    margin: 0 auto;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.card {
    border: none;
    border-radius: 16px;
    box-shadow: var(--card-shadow);
    transition: all 0.3s ease;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    margin-bottom: 2rem;
}

.card:hover {
    box-shadow: var(--hover-shadow);
    transform: translateY(-2px);
}

.card-header {
    background: transparent;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    padding: 1.5rem;
}

.card-header h3 {
    margin: 0;
    color: var(--primary-color);
    font-weight: 600;
}

.card-body {
    padding: 2rem;
}

/* 表单样式优化 */
.form-control, .form-select {
    border-radius: 12px;
    border: 1px solid rgba(0, 0, 0, 0.1);
    padding: 0.75rem 1rem;
    transition: all 0.3s ease;
    font-size: 1rem;
}

.form-control:focus, .form-select:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 0.2rem rgba(74, 107, 255, 0.15);
}

.form-label {
    font-weight: 500;
    margin-bottom: 0.5rem;
    color: #333;
}

.form-text {
    color: #666;
    font-size: 0.875rem;
    margin-top: 0.25rem;
}

/* 按钮样式优化 */
.btn-primary {
    background: var(--primary-color);
    border: none;
    border-radius: 12px;
    padding: 0.75rem 1.5rem;
    font-weight: 500;
    transition: all 0.3s ease;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.btn-primary:hover {
    background: var(--secondary-color);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(74, 107, 255, 0.3);
}

/* 表格样式优化 */
.table {
    border-radius: 12px;
    overflow: hidden;
    margin-bottom: 0;
}

.table th {
    text-align: center;
    vertical-align: middle;
    font-size: 0.9rem;
    font-weight: 600;
    background: rgba(74, 107, 255, 0.05);
    border-bottom: 2px solid rgba(0, 0, 0, 0.05);
    padding: 1rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    white-space: nowrap;
    width: 1%;
}

.table td {
    font-size: 0.9rem;
    vertical-align: middle;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    padding: 1rem;
}

.table-hover tbody tr {
    cursor: pointer;
    transition: all 0.3s ease;
}

.table-hover tbody tr:hover {
    background: rgba(74, 107, 255, 0.05);
    transform: translateX(5px);
}

/* 状态标签样式 */
.status-tag {
    display: inline-block;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.status-success {
    background: rgba(0, 200, 83, 0.1);
    color: var(--success-color);
}

.status-warning {
    background: rgba(255, 152, 0, 0.1);
    color: var(--warning-color);
}

.status-error {
    background: rgba(255, 71, 87, 0.1);
    color: var(--error-color);
}

/* 响应式设计优化 */
@media (max-width: 768px) {
    .card {
        margin: 1rem;
    }
    
    .card-body {
        padding: 1.5rem;
    }
    
    .table-responsive {
        margin: 0 -1rem;
    }
    
    .table th, .table td {
        padding: 0.75rem;
        font-size: 0.85rem;
    }
    
    .btn-primary {
        width: 100%;
    }
    
    .form-control, .form-select {
        font-size: 16px; /* 防止iOS自动缩放 */
    }
}

/* 动画效果 */
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.animate-fade-in {
    animation: fadeIn 0.5s ease-out forwards;
}

/* 快递公司图标 */
.carrier-icon {
    width: 24px;
    height: 24px;
    margin-right: 8px;
    vertical-align: middle;
}

/* 历史记录时间样式 */
.query-time {
    color: #666;
    font-size: 0.85rem;
}

/* 操作按钮样式 */
.action-btn {
    padding: 0.25rem 0.5rem;
    font-size: 0.85rem;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.action-btn:hover {
    transform: translateY(-1px);
}

/* 弹窗样式优化 */
#sf-modal-bg {
    position: fixed;
    left: 0; top: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,0.3);
    backdrop-filter: blur(5px);
    z-index: 2000;
    display: none;
    animation: fadeIn 0.3s ease-out;
}

#sf-modal {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: #fff;
    border-radius: 16px;
    box-shadow: var(--card-shadow);
    padding: 2rem 1.5rem 1.5rem 1.5rem;
    z-index: 2100;
    min-width: 260px;
    max-width: 90vw;
    display: none;
    animation: fadeIn 0.3s ease-out;
}

#sf-modal input {
    text-align: center;
    font-size: 1.2rem;
    letter-spacing: 0.2em;
    border-radius: 12px;
    padding: 1rem;
}

/* 错误提示样式 */
.error-message {
    color: var(--error-color);
    font-size: 0.9rem;
    margin-top: 0.5rem;
    display: none;
}

/* 成功提示样式 */
.success-message {
    color: var(--success-color);
    font-size: 0.9rem;
    margin-top: 0.5rem;
    display: none;
}

.main-card {
    border: none;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    margin-bottom: 2rem;
    padding: 2rem;
}

/* 时间轴样式补充 */
.kd-timeline {
    margin: 2rem 0 1rem 0;
    padding-left: 20px;
    border-left: 3px solid #e8edff;
    position: relative;
}
.kd-timeline-item {
    position: relative;
    margin-bottom: 2rem;
    padding-left: 20px;
}
.kd-timeline-item.active .kd-timeline-dot {
    background: #4a6bff;
    border-color: #4a6bff;
}
.kd-timeline-dot {
    position: absolute;
    left: -12px;
    top: 6px;
    width: 16px;
    height: 16px;
    background: #fff;
    border: 3px solid #e8edff;
    border-radius: 50%;
    z-index: 1;
    transition: background 0.3s, border-color 0.3s;
}
.kd-timeline-time {
    color: #888;
    font-size: 0.95rem;
    margin-bottom: 0.2rem;
}
.kd-timeline-content {
    font-size: 1rem;
    color: #333;
    line-height: 1.7;
    word-break: break-all;
}
.express-search-input {
    border-radius: 12px;
    border: 1px solid rgba(0, 0, 0, 0.1);
    padding: 0.75rem 1rem;
    font-size: 1rem;
    width: 70%;
    margin-right: 1rem;
    box-sizing: border-box;
}
.express-search-btn {
    background: #4a6bff;
    border: none;
    border-radius: 12px;
    padding: 0.75rem 1.5rem;
    font-weight: 500;
    color: #fff;
    font-size: 1rem;
    transition: all 0.3s ease;
    cursor: pointer;
}
.express-search-btn:hover {
    background: #6c8eff;
}
.table th.query-time-col, .table td.query-time-col {
    min-width: 140px;
    white-space: nowrap;
}
</style>

<?php include 'header.php'; ?>

<div class="container" style="max-width:900px;">
    <!-- 快递查询卡片 -->
    <div class="main-card">
        <h2 class="express-search-title">快递查询</h2>
        <form class="express-search-form" id="queryForm" method="POST" action="">
            <input type="text" class="express-search-input" id="tracking_number" name="tracking_number" placeholder="请输入快递单号" value="<?php echo isset($_POST['tracking_number']) ? htmlspecialchars($_POST['tracking_number']) : ''; ?>">
            <select class="form-select" id="carrier" name="carrier" style="width:150px;">
                <option value="">自动识别</option>
                <!-- <option value="sf" <?php if(isset($_POST['carrier']) && $_POST['carrier']=='sf') echo 'selected'; ?>>顺丰</option> -->
                <!-- 可根据需要添加其他快递公司 -->
            </select>
            <button type="submit" class="express-search-btn">查询</button>
        </form>
    </div>

    <!-- 查询结果卡片（如有结果） -->
    <?php if(isset($result)): ?>
    <div class="main-card" style="margin-top:2rem;">
        <?php 
        $carrier_name = '';
        if (isset($result['result']['type'])) {
            $carrier_code = strtolower($result['result']['type']);
            $carrier_name = isset($carrier_map[$carrier_code]) ? $carrier_map[$carrier_code] : $result['result']['type'];
        }
        ?>
        <div class="alert alert-info">
            快递公司：<?php echo !empty($carrier_name) ? htmlspecialchars($carrier_name) : '未识别'; ?>
        </div>
        <div class="kd-timeline">
            <?php 
            $list = $result['result']['list'] ?? [];
            foreach ($list as $i => $item):
                $isFirst = $i === 0;
                $time = !empty($item['time']) ? date('Y.m.d H:i', strtotime($item['time'])) : '';
                $context = isset($item['status']) ? $item['status'] : (isset($item['context']) ? $item['context'] : '');
            ?>
            <div class="kd-timeline-item<?php echo $isFirst ? ' active' : ''; ?>">
                <div class="kd-timeline-time">
                    <?php echo htmlspecialchars($time); ?>
                </div>
                <div class="kd-timeline-dot"></div>
                <div class="kd-timeline-content">
                    <?php echo nl2br(htmlspecialchars($context)); ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- 查询历史卡片 -->
    <?php if(isset($_SESSION['username']) && !empty($history)): ?>
    <div class="main-card" style="margin-top:2rem;">
        <h4 style="margin-bottom:1.5rem;">
            最近查询
            <span style="color:red; font-size:0.6em; margin-left:0.5rem;">(点击单号复制)</span>
        </h4>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>单号</th>
                        <th>快递公司</th>
                        <th>备注</th>
                        <th>快递状态</th>
                        <th>快递信息</th>
                        <th class="query-time-col">查询时间</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $unique_history = array();
                    foreach($history as $item) {
                        // 确保只处理当前用户的记录
                        if ($item['name'] == $_SESSION['username']) {
                            $tracking_number = explode(':', $item['tracking_number'])[0];
                            if (!isset($unique_history[$tracking_number])) {
                                $unique_history[$tracking_number] = $item;
                            }
                        }
                    }
                    foreach($unique_history as $item): 
                        $carrier_name = '';
                        if (!empty($item['carrier'])) {
                            $carrier_code = strtolower($item['carrier']);
                            $carrier_name = isset($carrier_map[$carrier_code]) ? $carrier_map[$carrier_code] : $item['carrier'];
                        }
                    ?>
                        <tr onclick="window.location.href='index.php?tracking_number=<?php echo $item['tracking_number']; ?><?php if(!empty($item['carrier'])) echo '&carrier=' . urlencode($item['carrier']); ?>'">
                            <td class="copy-tracking-number" data-number="<?php echo htmlspecialchars(explode(':', $item['tracking_number'])[0]); ?>" style="cursor:pointer; color:#4a6bff; text-decoration:underline;" onclick="event.stopPropagation(); copyTrackingNumber(this);">
                                <?php echo htmlspecialchars(explode(':', $item['tracking_number'])[0]); ?>
                            </td>
                            <td><?php echo !empty($carrier_name) ? htmlspecialchars($carrier_name) : '未识别'; ?></td>
                            <td>
                                <input type="text" class="form-control form-control-sm remark-input" 
                                    value="<?php echo htmlspecialchars($item['remark'] ?? ''); ?>" 
                                    maxlength="6" 
                                    data-id="<?php echo $item['id']; ?>"
                                    style="width:80px; display:inline-block; border:none; background:transparent; text-align:center; color:#FF8C00;"
                                    onchange="updateRemark(this)"
                                    onclick="event.stopPropagation();">
                            </td>
                            <td>
                                <?php 
                                if (!empty($item['express_status'])) {
                                    if ($item['express_status'] === '已妥投') {
                                        echo '<span style="color:#00c853;font-weight:bold;">' . htmlspecialchars($item['express_status']) . '</span>';
                                    } elseif ($item['express_status'] === '派送中') {
                                        echo '<span style="color:#ff4757;font-weight:bold;">' . htmlspecialchars($item['express_status']) . '</span>';
                                    } else {
                                        echo htmlspecialchars($item['express_status']);
                                    }
                                } else {
                                    echo '未知';
                                }
                                ?>
                            </td>
                            <td class="history-status">
                                <?php 
                                $status = isset($item['status']) ? (string)$item['status'] : '暂无状态';
                                if (mb_strlen($status, 'UTF-8') > 20) {
                                    echo mb_substr($status, 0, 20, 'UTF-8') . '...';
                                } else {
                                    echo $status;
                                }
                                ?>
                            </td>
                            <td class="query-time-col"><?php echo $item['query_time']; ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <!-- 错误提示卡片 -->
    <?php if (!empty($error)): ?>
    <div class="main-card" style="margin-top:2rem; color:#ff4757; font-weight:bold; text-align:center;">
        <?php echo htmlspecialchars($error); ?>
    </div>
    <?php endif; ?>
</div>

<!-- 顺丰弹窗 -->
<div id="sf-modal-bg"></div>
<div id="sf-modal">
    <div class="mb-3 text-center">
        <strong>顺丰快递需要输入手机号后四位</strong>
    </div>
    <input type="text" id="sf-phone" maxlength="4" class="form-control mb-3" placeholder="请输入手机号后四位">
    <div class="d-grid">
        <button class="btn btn-primary" id="sf-confirm">确定</button>
    </div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('queryForm');
    const carrierSelect = document.getElementById('carrier');
    const trackingInput = document.getElementById('tracking_number');
    const sfModalBg = document.getElementById('sf-modal-bg');
    const sfModal = document.getElementById('sf-modal');
    const sfPhone = document.getElementById('sf-phone');
    const sfConfirm = document.getElementById('sf-confirm');
    let sfPhoneValue = '';
    let allowSubmit = false;

    function isSF(tracking, carrier) {
        // 调试输出
        console.log('isSF判断:', tracking, carrier, carrier === 'sf', /^SF\d+/i.test(tracking));
        return carrier === 'sf' || (carrier === '' && /^SF\d+/i.test(tracking));
    }

    function showSFModal() {
        console.log('弹窗!');
        sfModalBg.style.display = 'block';
        sfModal.style.display = 'block';
        sfPhone.value = '';
        sfPhone.focus();
    }
    function hideSFModal() {
        sfModalBg.style.display = 'none';
        sfModal.style.display = 'none';
    }

    if (form) {
        form.addEventListener('submit', function(e) {
            const tracking = trackingInput.value.trim();
            const carrier = carrierSelect.value;
            console.log('提交时判断:', tracking, carrier, allowSubmit, isSF(tracking, carrier));
            if (isSF(tracking, carrier) && !allowSubmit) {
                e.preventDefault();
                showSFModal();
                return false;
            }
            if (isSF(tracking, carrier) && allowSubmit) {
                trackingInput.value = tracking + ':' + sfPhoneValue;
                setTimeout(() => {
                    trackingInput.value = tracking;
                    sfPhoneValue = '';
                    allowSubmit = false;
                }, 100);
            } else {
                sfPhoneValue = '';
                allowSubmit = false;
            }
        });
    }

    if (sfConfirm) {
        sfConfirm.onclick = function() {
            const phone = sfPhone.value.trim();
            if (!/^\d{4}$/.test(phone)) {
                sfPhone.classList.add('is-invalid');
                sfPhone.focus();
                return;
            }
            sfPhone.classList.remove('is-invalid');
            sfPhoneValue = phone;
            hideSFModal();
            allowSubmit = true;
            form.requestSubmit();
        };
    }
    if (sfModalBg) {
        sfModalBg.onclick = function() {
            hideSFModal();
        };
    }
});

function showLoading() {
    const loading = document.createElement('div');
    loading.className = 'loading';
    loading.innerHTML = '<div class="loading-spinner"></div><p>正在查询中...</p>';
    document.querySelector('.card-body').appendChild(loading);
}

function showError(input, message) {
    let errorDiv = input.nextElementSibling;
    if (!errorDiv || !errorDiv.classList.contains('error-message')) {
        errorDiv = document.createElement('div');
        errorDiv.className = 'error-message';
        input.parentNode.insertBefore(errorDiv, input.nextSibling);
    }
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';
    input.classList.add('is-invalid');
}

function hideError(input) {
    const errorDiv = input.nextElementSibling;
    if (errorDiv && errorDiv.classList.contains('error-message')) {
        errorDiv.style.display = 'none';
    }
    input.classList.remove('is-invalid');
}

// 快递公司选择
document.querySelectorAll('.express-company-item').forEach(item => {
    item.addEventListener('click', function() {
        const carrier = this.getAttribute('data-carrier');
        const form = document.querySelector('.express-search-form');
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'carrier';
        input.value = carrier;
        form.appendChild(input);
        form.submit();
    });
});

// 分享功能
function shareResult() {
    // 实现分享功能
    alert('分享功能开发中...');
}

// 打印功能
function printResult() {
    window.print();
}

function copyTrackingNumber(el) {
    const number = el.getAttribute('data-number');
    if (!number) return;
    if (navigator.clipboard) {
        navigator.clipboard.writeText(number).then(function() {
            showCopyTip(el, '已复制');
        }, function() {
            showCopyTip(el, '复制失败');
        });
    } else {
        // 兼容旧浏览器
        const textarea = document.createElement('textarea');
        textarea.value = number;
        document.body.appendChild(textarea);
        textarea.select();
        try {
            document.execCommand('copy');
            showCopyTip(el, '已复制');
        } catch (err) {
            showCopyTip(el, '复制失败');
        }
        document.body.removeChild(textarea);
    }
}
function showCopyTip(el, msg) {
    let tip = document.createElement('span');
    tip.textContent = msg;
    tip.style.position = 'absolute';
    tip.style.background = '#333';
    tip.style.color = '#fff';
    tip.style.fontSize = '0.85rem';
    tip.style.padding = '2px 8px';
    tip.style.borderRadius = '6px';
    tip.style.left = (el.offsetLeft + el.offsetWidth/2 - 20) + 'px';
    tip.style.top = (el.offsetTop - 28) + 'px';
    tip.style.zIndex = 9999;
    tip.style.pointerEvents = 'none';
    tip.style.transition = 'opacity 0.3s';
    tip.style.opacity = 1;
    el.parentNode.style.position = 'relative';
    el.parentNode.appendChild(tip);
    setTimeout(function() {
        tip.style.opacity = 0;
        setTimeout(function() {
            if (tip.parentNode) tip.parentNode.removeChild(tip);
        }, 300);
    }, 1000);
}

document.addEventListener('DOMContentLoaded', function() {
    var tbody = document.querySelector('.table tbody');
    if (tbody) {
        tbody.addEventListener('click', function(e) {
            var btn = e.target.closest('.delete-history-btn');
            if (btn) {
                e.preventDefault();
                e.stopPropagation();
                if (!confirm('确定要删除这条记录吗？')) return;
                var id = btn.getAttribute('data-id');
                var row = btn.closest('tr');
                fetch('history.php?delete=' + encodeURIComponent(id) + '&ajax=1', {
                    method: 'GET',
                    credentials: 'same-origin'
                })
                .then(function(res) { return res.text(); })
                .then(function(text) {
                    if (text.trim() === 'ok') {
                        if (row) row.parentNode.removeChild(row);
                    } else {
                        alert('删除失败');
                    }
                })
                .catch(function() {
                    alert('请求失败');
                });
            }
        });
    }
});

function updateRemark(input) {
    const id = input.getAttribute('data-id');
    const remark = input.value.trim();
    
    // 检查字符长度
    if (remark.length > 6) {
        showCopyTip(input, '备注不能超过6个字符');
        input.value = input.value.slice(0, 6); // 截取前6个字符
        return;
    }
    
    // 发送AJAX请求更新备注
    fetch('update_remark.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `id=${id}&remark=${encodeURIComponent(remark)}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新成功
            showCopyTip(input, '备注已保存');
        } else {
            // 更新失败
            showCopyTip(input, '保存失败');
            input.value = data.original_remark || '';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showCopyTip(input, '保存失败');
    });
}

// 添加输入事件监听
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.remark-input').forEach(input => {
        input.addEventListener('input', function(e) {
            if (this.value.length > 6) {
                showCopyTip(this, '备注不能超过6个字符');
                this.value = this.value.slice(0, 6); // 截取前6个字符
            }
        });
    });
});
</script>

<?php include 'footer.php'; ?> 